package util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Excel导出的工具类
 * @author Lesson
 *
 */
public class ExportExcel {
		
		/**
		 * 
		 * @param list  加载的数据集
		 * @param fileName   下载的execl的名称
		 * @param response   响应客户端
		 * @param hreadMap   如果数据集为空，需要设定表头
		 * @throws IOException
		 */
	    public static void export(List<Map> list, String fileName, HttpServletResponse response, Map hreadMap) throws IOException {
	        HSSFWorkbook wb = new HSSFWorkbook();  
	        HSSFSheet sheet = wb.createSheet("sheet1");  
	        HSSFRow row = sheet.createRow((int) 0);  
	        HSSFCellStyle style = wb.createCellStyle();  
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
	        
	    	Iterator<Map.Entry<String, String>> it =null;
	        if(list == null || list.size()==0){
	        	it = hreadMap.entrySet().iterator();
	        }else{
	        	it = list.get(0).entrySet().iterator();
	        }
       
        	int k = 0;
        	while (it.hasNext()) {
        		Map.Entry<String, String> entry = it.next();
        		HSSFCell cell = row.createCell(k);  
	            cell.setCellValue(entry.getKey());  
	            cell.setCellStyle(style);  
	            sheet.autoSizeColumn(k);  
	            k++;
			}

	        for (int i = 0; i < list.size(); i++) {
	        	 row = sheet.createRow(i + 1);  
	        	Iterator<Map.Entry<String, String>> its = list.get(i).entrySet().iterator();
	        	int s = 0;
	    		while (its.hasNext()) {
	    			Map.Entry<String, String> entry = its.next();
	    			Object obj = entry.getValue();
	    			row.createCell(s).setCellValue(obj.toString());
	    			s++;
	    		}
	        }  
	        
	        response.reset();
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");    
		    response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1")+".xlsx"); 
		    wb.write(response.getOutputStream());
		    response.flushBuffer();
		    
	    }  
}
